package ca.paulshin.yunatube.services;

import java.util.Locale;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import ca.paulshin.yunatube.R;
import ca.paulshin.yunatube.YunaTubeApplication;
import ca.paulshin.yunatube.aboutyuna.WebViewFragment;
import ca.paulshin.yunatube.common.Constants;
import ca.paulshin.yunatube.common.Preference;
import ca.paulshin.yunatube.common.Utils;
import ca.paulshin.yunatube.main.HotNewsActivity;
import ca.paulshin.yunatube.main.MainActivity;
import ca.paulshin.yunatube.services.broadcast.GCMBroadcastReceiver;
import ca.paulshin.yunatube.youtube.YouTubeActivity;

import com.google.android.gms.gcm.GoogleCloudMessaging;

public class GCMIntentService extends IntentService {
    public static final int NOTIFICATION_ID = 1;
    private static final String TAG = "GCM";
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    
    public static final String EXTRA_DO_UPDATE = "do_update";

    public GCMIntentService() {
        super("GCMIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
//        	Log.d("log", extras.toString());
            /*
             * Filter messages based on message type. Since it is likely that GCM
             * will be extended in the future with new message types, just ignore
             * any message types you're not interested in, or that you don't
             * recognize.
             */
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
//                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
//                sendNotification("Deleted messages on server: " + extras.toString());
            // If it's a regular GCM message, do some work.
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                // Post notification of received message.
                sendNotification(extras);
                Utils.debug(TAG, "Received: " + extras.toString());
            }
        }
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GCMBroadcastReceiver.completeWakefulIntent(intent);
    }

    // Put the message into a notification and post it.
    private void sendNotification(Bundle bundle) {
    	if (YunaTubeApplication.debuggable)
    		Utils.debug(bundle.toString());
    	
    	// Filter bundle
    	if (TextUtils.equals("Y", bundle.getString("DO_UPDATE")))
    		Preference.put(EXTRA_DO_UPDATE, true); // Actual update will be run in MainActivity
    	
    	String locale = getResources().getConfiguration().locale.toString();
    	boolean isKorean = Locale.KOREA.toString().contains(locale);
    	
    	if (isKorean && (
    			TextUtils.equals("Y", bundle.getString("MARKET_UPDATE")) || TextUtils.equals("Y", bundle.getString("SURVEY")) || (
    					Preference.getBoolean(Constants.NOTIFICATION) && TextUtils.equals("Y", bundle.getString("SHOW_NOTIFICATION")))
    					)
    		) {
    		String titleText = bundle.getString("TITLE");
    		String contentText = bundle.getString("CONTENT");
    		String contentInfo = bundle.getString("CONTENT_INFO");
    		String urlText = bundle.getString("URL");
    		String youtubeText = bundle.getString("YOUTUBE");
    		
    		mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            PendingIntent contentIntent = null;
            Intent intent = null;
            
            if (TextUtils.equals("Y", bundle.getString("MARKET_UPDATE"))) {
            	intent = new Intent(Intent.ACTION_VIEW);
            	intent.setData(Uri.parse("market://details?id=ca.paulshin.yunatube"));
            }
            else if (TextUtils.equals("Y", bundle.getString("SURVEY"))) {
            	// Redirect to Survey activity
            	intent = new Intent(this, MainActivity.class);
    			String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
            	intent.putExtra(MainActivity.EXTRA_FRAGMENT, WebViewFragment.class);
            	intent.putExtra(WebViewFragment.EXTRA_TITLE, R.string.supermenu_survey);
            	intent.putExtra(WebViewFragment.EXTRA_URL, Constants.SURVEY_URL + deviceId);
            }
            else if (TextUtils.isEmpty(urlText) && TextUtils.isEmpty(youtubeText)) {
            	// Redirect to HotNews activity
            	intent = new Intent(this, HotNewsActivity.class);
            	intent.putExtra(HotNewsActivity.EXTRA_FROM_GCM, true);
            }
            else if (!TextUtils.isEmpty(urlText)) {
            	// Launch a browser
            	Uri uri = Uri.parse(urlText);
            	intent = new Intent(Intent.ACTION_VIEW, uri);
            }
            else if (!TextUtils.isEmpty(youtubeText)) {
            	// Redirect to YouTube activity
            	Bundle youtubeBundle = new Bundle();
            	youtubeBundle.putStringArray(YouTubeActivity.EXTRA_YOUTUBE_CLIPSET, new String[] { getString(R.string.hot_news_title), titleText, youtubeText });
            	intent = new Intent(this, YouTubeActivity.class);
            	intent.putExtras(youtubeBundle);
            }

        	contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
        	
            int bigIcons [] = {R.drawable.ic_notification_1, R.drawable.ic_notification_2, R.drawable.ic_notification_3, R.drawable.ic_notification_4, R.drawable.ic_notification_5};
            int randomIndex = (int)(Math.random() * bigIcons.length);
            
            Bitmap icon = BitmapFactory.decodeResource(getResources(), bigIcons[randomIndex]);
            
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_action_star)
            .setContentTitle(titleText)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(contentText).setBigContentTitle(titleText).setSummaryText(contentInfo))
            .setLargeIcon(icon)
            .setContentText(contentText);

            mBuilder.setContentIntent(contentIntent);
            mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
            
            // Ref: http://developer.android.com/guide/topics/ui/notifiers/notifications.html#ApplyStyle
    	}
    }
}